#include <math.h>
#include <float.h>
#include <string>
#include <cstdlib>
#include <cstdio>
#include <cctype>
#include "rules/rules.h"
#include "functions.h"

static double tenpow(int n) {
    double y = 10.0;
    while (--n > 0)
        y *= 10.0;
    return y;
}

static int nMax = DBL_DIG;

double round(double x, int n) {
    bool neg = (x < 0.0);
    double ipart, fpart;
    double y, p;
    if (neg)
        x = -x;
    if (n > 0) {
        double yy;
        fpart = modf(x, &ipart);
        if (n > nMax)
            n = nMax;
        p = tenpow(n);
        y = fpart * p;
        fpart = modf(y, &yy);
        if (fpart < 0.5)
            yy += 1.0;
        y = ipart + yy / p;
    } else if (n < 0) {
        if (n < -nMax)
            n = -nMax;
        p = tenpow(-n);
        y = x / p;
        y = round(y, 0) * p;
    } else { /* n == 0 */
        fpart = modf(x, &ipart);
        y = (fpart < 0.5) ? ipart : ipart + 1;
    }
    return neg ? -y : y;
}

std::string genKey(char type_cle, unsigned long int iter, unsigned int *seed, bool *rules) {
    std::string key = "";
    char i = 0;
    std::string charset = rule1(type_cle);
    for (i = 0; i < 26; i++) {
        key += charset[rand_r(seed) % (charset.length())];
    }
    if (rules[2])
        key[22] = rule2(type_cle, seed);
    if (rules[10])
        if (type_cle == true) key = rule10(key, iter, seed);
    return key;
}

bool nbChiffres(std::string key, int n) {
    int nChiffres = 0;
    for (int i = 0; i < key.length(); i++) {
        if (isdigit(key[i])) {
            nChiffres++;
        }
    }
    return (nChiffres == n);
}
